<template>
  <view class="container">
    <scroll-view scroll-y>
      <!-- 头部搜索 -->
      <view class="search">
        <Search :isOpenbgImg="false" />
      </view>
      <!-- 任务列表 -->
      <!-- 
        checkboxChange：更改任务状态
        deleteTask：删除任务
        checkTask：查看任务
        editCheck：选中任务
        selectAll：全选
        moveTask：显示任务分类列表
       -->
      <view class="content">
        <TaskList
          :taskList="taskList"
          :isShowConfirm="isShowConfirm"
          v-on:checkboxChange="checkboxChange"
          v-on:deleteTask="deleteTask"
          v-on:checkTask="checkTask"
          v-on:editCheck="editCheck"
          v-on:selectAll="selectAll"
          v-on:moveTask="isShowTaskType = true"
          v-on:showConfirm="isShowConfirm = true"
          v-on:closeConfirm="isShowConfirm = false"
        ></TaskList>
      </view>

      <!-- 任务分类 -->
      <task-type
        :taskTypeId="uuid"
        :taskTypeList="taskTypeList"
        v-show="isShowTaskType"
        v-on:cancel="isShowTaskType = false"
        v-on:getTaskItem="getTaskItem"
      />
    </scroll-view>
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import Search from "../../component/Search/Search";
import TaskList from "../../component/TaskList/TaskList";
import TaskType from "../../component/TaskType/TaskType";

// 引入接口文件
const {
  getWorksByOp,
  changeWorkStatus,
  changeWorkInfo,
  delWork,
} = require("../../api/home/task");

export default {
  props: {},
  components: { Search, TaskList, TaskType },
  data() {
    return {
      isShowTaskType: false, // 是否显示任务列表
      isShowConfirm: false, // 是否显示确认删除
      isSelectAll: true, // 是否全选
      taskList: [], // 任务项数据
      uuid: "",
    };
  },
  computed: {
    ...mapState(["taskTypeList"]),
  },
  watch: {},
  methods: {
    ...mapMutations(["editIsGetDataAgain"]),

    // 更改任务状态
    checkboxChange(params) {
      const { status, uuid, taskTime } = params;
      let taskType = "unfinish";
      let index = -1;

      for (let i = 0; i < this.taskList.length; i++) {
        // 如果找到日期才继续往下找
        if (this.taskList[i].time == taskTime) {
          taskType = "unfinish";
          index = this.taskList[i]["unfinish"].findIndex(item => {
            return item.uuid == uuid;
          });
          if (index == -1) {
            taskType = "finish";
            index = this.taskList[i]["finish"].findIndex(item => {
              return item.uuid == uuid;
            });
          }
          // console.log(this.taskList[i], taskType, index, status);
          if (index != -1) {
            // 更改任务状态请求
            changeWorkStatus({ wid: uuid }).then(res => {
              this.taskList[i][taskType][index].w_status = status;
            });
            break; // 跳出循环
          }
        }
      }
    },
    // 删除任务
    deleteTask() {
      // 获取被选中的任务项
      let selectTaskList = new Set();
      this.taskList.forEach(item => {
        item.unfinish.forEach(unfinish => {
          if (unfinish.isSelect == true) selectTaskList.add(unfinish.uuid);
        });
        item.finish.forEach(finish => {
          if (finish.isSelect == true) selectTaskList.add(finish.uuid);
        });
      });
      if (selectTaskList.size == 0)
        return uni.showToast({ title: "请选择要删除的任务！", icon: "none" });

      let flag = true;
      let asyncFun = [];
      selectTaskList.forEach(item => {
        asyncFun.push(
          delWork({ wid: item }).then(
            res => (flag = true),
            err => (flag = false)
          )
        );
      });
      Promise.all(asyncFun).then(async res => {
        await this.getTaskList(); // 刷新数据
        flag
          ? uni.showToast({ title: "删除成功！", icon: "none" })
          : uni.showToast({ title: "删除失败！", icon: "none" });
        // 需要重新获取数据
        this.editIsGetDataAgain(true);
        this.isShowConfirm = false;
      });
    },
    // 转移任务 params:任务分类数据
    getTaskItem(params) {
      let selectTaskList = new Set();
      this.taskList.forEach(item => {
        item.unfinish.forEach(unfinish => {
          if (unfinish.isSelect == true) selectTaskList.add(unfinish.uuid);
        });
        item.finish.forEach(finish => {
          if (finish.isSelect == true) selectTaskList.add(finish.uuid);
        });
      });
      if (selectTaskList.size == 0)
        return uni.showToast({ title: "请选择要转移的任务！", icon: "none" });

      let flag = true;
      let asyncFun = [];
      selectTaskList.forEach(uuid => {
        asyncFun.push(
          changeWorkInfo({ wid: uuid, opid: params.oid }).then(
            res => (flag = true),
            err => (flag = false)
          )
        );
      });
      Promise.all(asyncFun)
        .then(async () => {
          // 需要重新获取数据
          this.editIsGetDataAgain(true);
          await this.getTaskList(); // 刷新数据
        })
        .then(() => {
          flag
            ? uni.showToast({ title: "转移成功！", icon: "none" })
            : uni.showToast({ title: "转移失败！", icon: "none" });
          this.isShowTaskType = false;
        });
    },
    // 查看任务
    checkTask(uuid) {
      if (uuid == "") return;
      uni.navigateTo({
        url: "../addtask/addtask?uuid=" + uuid,
      });
    },
    // 选中任务(单个)
    editCheck(params) {
      const { index, serial, taskType } = params;
      let isSelect = this.taskList[index][taskType][serial].isSelect;

      this.taskList[index][taskType][serial].isSelect = !isSelect;
    },
    // 全选
    selectAll() {
      this.taskList.forEach(item => {
        item.unfinish.forEach(
          unfinish => (unfinish.isSelect = this.isSelectAll)
        );
        item.finish.forEach(finish => (finish.isSelect = this.isSelectAll));
      });
      this.isSelectAll = !this.isSelectAll;
    },
    // 获取任务数据
    getTaskList() {
      let params = {
        opid: this.uuid,
        code: uni.getStorageSync("openId"),
      };
      getWorksByOp(params).then(
        res => {
          if (!res) return (this.taskList = []);

          res.forEach(item => {
            if (item.unfinish) {
              // 添加是否选中的属性
              item.unfinish.forEach(unfinish => {
                unfinish.isSelect = false;
                unfinish.listType = "unfinish";
              });
            }
            if (item.finish) {
              // 添加是否选中的属性
              item.finish.forEach(finish => {
                finish.isSelect = false;
                finish.listType = "finish";
              });
            }
          });
          this.taskList = res;
        },
        err => {
          console.log(err);
          this.taskList = [];
        }
      );
    },
  },
  onLoad(options) {
    this.uuid = options.uuid;
    // 获取数据
    this.getTaskList();
  },
  mounted() {},
  beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.container {
  // 头部搜索
  .search {
    height: 8%;
    padding: 10rpx 30rpx;
    background-color: #fff;
  }
}
</style>
